package cn.ronghuanet.auth.interceptors;

import cn.ronghuanet.auth.annotation.RonghuaPermission;
import cn.ronghuanet.base.util.LoginContext;
import cn.ronghuanet.org.domain.Employee;
import cn.ronghuanet.org.service.IEmployeeServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private IEmployeeServiceI service;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 前端的token是放在header里面的
        String token = request.getHeader("token");
        System.out.println(token);
        if (StringUtils.isEmpty(token)){
            System.out.println("没有传入token");

            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;
        }
        Employee user = (Employee)LoginContext.loginMap.get(token);
        if (Objects.isNull(user)){
            System.out.println("token取值错误");
            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;
        }
        // 对于url路径的权限控制
        // 1. 判断用户访问的这个资源 需要权限不?
        HandlerMethod methodHandle= (HandlerMethod)handler;
        RonghuaPermission methodAnnotation = methodHandle.getMethodAnnotation(RonghuaPermission.class);
        if (Objects.nonNull(methodAnnotation)){
            // 2. 如果需要权限 判断用户是否有权限
            // 2.1 首先拿到用户的权限  通过用户拿
            List<String> list = service.queryPermissionByUserId(user.getId());
            // 2.2 在拿当前资源的权限 /emp/list(资源权限)  emp:list(用户的权限)
            Method method = methodHandle.getMethod();

            String mP = method.getDeclaringClass().getSimpleName() +":"+method.getName();
            // 2.3 比较用户的权限和资源的权限  如果比对上就放行 否则 拦截
            if (!list.contains(mP)){
                System.out.println("无权访问.................");
                response.getWriter().print("{\"success\":false,\"msg\":\"NoPermission\"}");
                return  false;
            }
        }

        return true;
    }
}
